<template>
  <div ref="dom" class="charts chart-pie"></div>
</template>

<script>
  import echarts from 'echarts'
  import tdTheme from './theme.json'
  import {on, off} from '@/base/util/tools'

  echarts.registerTheme('tdTheme', tdTheme)
  export default {
    name: 'ChartPie',
    props: {
      value: Array,
      text: String,
      subtext: String
    },
    data() {
      return {
        dom: null
      }
    },
    methods: {
      resize() {
        this.dom.resize()
      },
      drawbarChart() {
        let legend = this.value.map(_ => _.name)
        let option = {
          grid: {
            x: '30 %'
          },
          title: {
            text: this.text,
            subtext: this.subtext,
            top: 'center',
            left: 'center',
            textStyle: {
              fontSize: 15
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b} : ({d}%)'
          },
          legend: {
            orient: 'vertical',
            x: '70%',
            y: 'center',
            data: legend,
            icon: 'circle',
            textStyle: {
              color: '#00E4FF'
            }
          },
          series: [
            {
              type: 'pie',
              center: ['50%', '50%'],
              radius: ['40%', '65%'],
              data: this.value,
              avoidLabelOverlap: false,
              label: {
                center: true,
                normal: {
                  show: true,
                  position: 'outter',
                  formatter: function (parms) {
                    return parms.data.legendname
                  }
                }
              },
              labelLine: {
                normal: {
                  length: 5,
                  length2: 3,
                  smooth: true
                }
              }
            }
          ]
        }
        this.dom = echarts.init(this.$refs.dom, 'tdTheme')
        this.dom.setOption(option)
        on(window, 'resize', this.resize)
      }
    },
    watch: {
      value() {
        this.drawbarChart()
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.drawbarChart()
      })
    },
    beforeDestroy() {
      off(window, 'resize', this.resize)
    }
  }
</script>
